<template>
  <!-- 管控排查 -->
  <view class="controlCheck-container">
    <u-navbar placeholder :auto-back="false" @leftClick="handleBack()">
      <view slot="center" style="width: 70vw">
        <TopBar :tabBars="tabBars" :tabIndex="tabIndex" @change="onTabChange" backgroundColor="#fff" />
      </view>
    </u-navbar>

    <view class="apply-body">
      <component
        v-if="ticketApplyResp.length || Object.keys(ticketApplyResp).length"
        ref="comp"
        v-bind:is="currentTabComponent"
        :data="ticketApplyResp"
        :projectInfo="projectInfo"
        :directorFlag="directorFlag"
        :btn-visible="btnVisible"
      />
      <Empty v-else />
    </view>
    <view v-if="btnVisible" class="submit-group">
      <button class="u-button new-btn" :ripple="true" @click="addNew">添加新票</button>
      <button class="u-button" :ripple="true" @click="submitApply">提交申请</button>
    </view>
  </view>
</template>

<script>
import Empty from '@/components/cu-empty/index.vue'
import TopBar from '@/components/top-bar/index.vue'
import ProjectInfo from './components/projectInfo.vue'
import WorkType from './components/workType.vue'
import CuFilter from '@/components/cu-filter/cu-filter.vue'
import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import CuCell from '@/components/cu-cell/cu-cell.vue'
import CuCellSelect from '@/components/cu-cell/cu-cell-select.vue'
import UserSelector from '@/components/user-selector/index.vue'
import DictPicker from '@/components/dict-picker/index.vue'
import CuSelect from '@/components/CuSelect/index.vue'
import { getTicketProInfo, getTicketWorkType, ticketApply } from '../../../api/spw/ticketApply'
import UNavbar from '@/uni_modules/uview-ui/components/u-navbar/u-navbar.vue'

export default {
  components: {
    UNavbar,
    Empty,
    TopBar,
    ProjectInfo,
    WorkType,
    CuFilter,
    CuCellGroup,
    CuCell,
    CuCellSelect,
    UserSelector,
    DictPicker,
    CuSelect
  },
  computed: {
    currentTabComponent() {
      return this.tabBars.find((item) => item.index === this.tabIndex).componentName
    },
    btnVisible() {
      return this.directorFlag === 'Y' && this.tabIndex === 0
    }
  },

  data() {
    return {
      projectInfo: {},
      cacheNewTickets: [],
      textColor: true,
      ticketApplyResp: [],
      pageNum: 1,
      tabBars: [
        {
          name: '作业类型',
          componentName: 'WorkType',
          index: 0
        },
        {
          name: '项目信息',
          componentName: 'ProjectInfo',
          index: 1
        }
      ],
      tabIndex: 0,
      projectId: '',
      projectInfoId: '',
      ticketLevelStatus: '',
      directorFlag: ''
    }
  },
  onBackPress(options) {
    return this.backConfirm(options)
  },
  onLoad(option) {
    const { projectInfoId, ticketLevelStatus, directorFlag, projectId } = option
    this.projectInfoId = projectInfoId
    this.projectId = projectId
    this.directorFlag = directorFlag
    this.$store.dispatch('specialWork/toggleStatus', ticketLevelStatus)
    this.initData()
  },
  methods: {
    handleBack() {
      if (!this.backConfirm({from: 'backbutton'})) {
        uni.navigateBack()
      }
    },
    backConfirm(options) {
      let some = this.ticketApplyResp.some((d) => {
        return d.ticketInfo
      })
      let someNewTicket = this.ticketApplyResp.some((d) => {
        return d.newTicket && (!d.ticketInfo || !Object.keys(d.ticketInfo).length)
      })

      if (options.from === 'backbutton' && (some || someNewTicket)) {
        let content = ''
        if (some) {
          content = `当前填写的作业票还未提交申请，确认返回？`
        } else if (someNewTicket) {
          content = `当前存在未填写的新作业票，返回后数据不会保留，确认返回？`
        }
        this.$modal.confirm(content).then(() => {
          uni.navigateBack()
        })
        return true
      }
      return false
    },
    onTabChange(obj) {
      if (this.tabIndex === obj.index) {
        return
      }
      this.tabIndex = obj.index
    },
    async initData() {
      const [res1, res2] = await Promise.all([
        getTicketWorkType(this.projectInfoId),
        getTicketProInfo(this.projectInfoId)
      ])
      this.ticketApplyResp = res1.data
      this.projectInfo = res2.data
    },
    addNew() {
      uni.navigateTo({
        url: `/pages/jobSlip/work-ticket/new-ticket?projectInfoId=${this.projectInfoId}&projectId=${this.projectId}`,
        events: {
          'new-ticket:form:success': (data) => {
            this.ticketApplyResp.unshift({
              ...data,
              newTicket: true
            })
          }
        }
      })
    },
    _submit() {
      this.submitLoading = true
      let dt = this.$refs.comp.data
      const req = []

      dt.forEach((item) => {
        const { ticketInfo, ticketId } = item
        if (ticketInfo) {
          ticketInfo.safetyMeasureContent = ticketInfo.safetyMeas
          item.safetyMeasureContent = ticketInfo.safetyMeas
          // 删除数据量可能会很大的字段
          const ticketContent = JSON.parse(JSON.stringify(ticketInfo))
          delete ticketContent.nodeAttrs
          delete ticketContent.riskIdentification
          delete ticketContent.riskIdentificationArr
          delete ticketContent.safetyMeas
          delete ticketContent.safetyMeasureContent
          delete ticketContent.staffs
          console.log('ticketContent', ticketContent)
          req.push({
            ...item,
            startTime: ticketInfo.startTime,
            endTime: ticketInfo.endTime,
            procDefId: ticketInfo.procDefId,
            staffs: ticketInfo.staffs,
            ticketContent: JSON.stringify(ticketContent),
            ticketWorkLevel: ticketInfo.workLevel,
            ticketWorkLevelLabel: ticketInfo.workLevelLabel,
            ticketWorkLevelKey: ticketInfo.ticketWorkLevelKey,
            workId: ticketInfo.workId,
            workType: ticketInfo.workType,
            fenceCoordinates: ticketInfo.electronicFenceCoordinates || [],
            fenceImgUrl: ticketInfo.electronicFenceImage || '',
            fenceExtrudeHeight: ticketInfo.electronicFenceExtrudeHeight || 0,
            fenceHeight: ticketInfo.electronicFenceHeight || 0,
            relateBlandPlateTicketId: ticketInfo.relateBlandPlateTicketId || '',
            blandPlateType: ticketInfo.blandPlateType || '',
            mediaLibIds: ticketInfo.libId ? ticketInfo.libId.join(',') : ''
          })
        } else if (ticketId) {
          req.push({
            ticketId: ticketId
          })
        }
      })
      if (!req.length) {
        this.$modal.showToast('请至少完善一项未填写的作业票信息')
        this.submitLoading = false
        return
      }
      console.log('作业票数据', req)
      ticketApply(this.projectInfoId, req)
        .then((res) => {
          uni.navigateBack()
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    submitApply() {
      if (this.submitLoading) {
        return
      }
      let someNewTicket = this.ticketApplyResp.some((d) => {
        return d.newTicket && (!d.ticketInfo || !Object.keys(d.ticketInfo).length)
      })
      if (someNewTicket) {
        this.$modal.confirm('存在未填写的新作业票，未填写的作业票不会被提交，是否确定提交申请？').then(() => {
          this._submit()
        })
        return
      }
      this._submit()
    }
  }
}
</script>

<style lang="scss" scoped>
.check {
  position: relative;

  .title {
    font-size: 34rpx;
    font-weight: 700;
    position: relative;

    .task-status {
      position: absolute;
      top: 10rpx;
      right: 0;

      .icon-style {
        width: 100rpx;
        height: 88rpx;
      }
    }
  }

  .icon-style {
    width: 52rpx;
    height: 52rpx;
    margin-right: 20rpx;
  }

  .text {
    color: #999;

    text {
      width: 62%;
      color: #333;
      display: inline-block;
    }

    .bg-select {
      display: inline-block;
      margin-left: 5px;

      i {
        display: inline-block;
        font-style: normal;
        margin-right: 5px;
      }

      &.level_1 {
        color: #a14430;
      }

      &.level_2 {
        color: #c87c32;
      }

      &.level_3 {
        color: #c4c088;
      }

      &.level_4 {
        color: #88b4c4;
      }
    }

    .text-right {
      width: 76%;
      text-align: left;
      // height: 76rpx;
      overflow: hidden;
    }

    .text-right1 {
      width: 68%;
    }
  }

  .flex-text {
    padding-top: 24rpx;
    display: flex;
    color: #999;

    text {
      color: #333;
      display: inline-block;
    }
  }

  .deal-btn {
    width: 22vw;
  }

  .report-btn {
    width: 36vw;
  }

  .bor-top {
    display: flex;
    align-items: center;
    padding-top: 20rpx;
    border-top: 1px solid #d5d7e3;
  }
}


.new-btn {
  background: #fff;
  color: #dd524d;
  border: 1px solid #f0ad4e;
}
</style>
